package mail

import (
	"bytes"
	c "gitee.com/lidongyooo/goblog/config"
	"gitee.com/lidongyooo/goblog/pkg/config"
	"gitee.com/lidongyooo/goblog/pkg/logger"
	"gitee.com/lidongyooo/goblog/pkg/route"
	"gopkg.in/gomail.v2"
	"html/template"
	"path"
	"strings"
)

var mailer *gomail.Dialer

func init() {
	c.Initialize()
	mailer = gomail.NewDialer(config.GetString("mail.host"), config.GetInt("mail.port"), config.GetString("mail.username"), config.GetString("mail.password"))
}

//邮件发送带解析模板
func SendWithTemplate(tplName string, data interface{}, to, subject string) error {
	tplName = strings.Replace(tplName, ".", "/", -1)
	tplFile := "resources/views/" + tplName + ".gohtml"

	t, err := template.New(path.Base(tplFile)).Funcs(template.FuncMap{
			"RouteName2URL": route.Name2URL,
		}).ParseFiles(tplFile)

	var tpl bytes.Buffer
	if err = t.Execute(&tpl, data); err != nil {
		logger.LogError(err)
		return err
	}

	return Send(to, subject, tpl.String())
}

//邮件发送
func Send(to, subject, body string) (err error) {
	m := gomail.NewMessage()
	m.SetHeader("From", "2271439559@qq.com")
	m.SetHeader("To", to)
	m.SetHeader("Subject", subject)
	m.SetBody("text/html", body)

	if err = mailer.DialAndSend(m); err != nil{
		logger.LogError(err)
	}

	return err
}
